﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.SessionState;
using Kaiser.Extensions;
using Kaiser.Infrastructure.Context;
using Kaiser.Infrastructure.Controllers;
using Kaiser.Infrastructure.User;
using Kaiser.Models;
using Kaiser.Models.JsonModels;
using Kaiser.Models.ViewModels;
using Kaiser.Modules.Admin.Extensions;
using Kaiser.Services;
using Kaiser.Models.InputModels;
using Kaiser.Utilities.Captcha;

namespace Kaiser.Modules.Admin.Controllers
{
    public class AdminController : KaiserBaseController
    {
        private readonly IUserService _userService;
        public AdminController(IUserService userService, ISystemManageService systemManageService)
        {
            _userService = userService;
            _systemManageService = systemManageService;

        }

        private ISystemManageService _systemManageService;

        public ISystemManageService SystemManageService
        {
            get { return _systemManageService; }
            set { _systemManageService = value; }
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(string oldPassword, string newPassword)
        {
            var vmobject = new JsonReturnMessages();

            try
            {
                if (_userService.GetItem(CurrentUser.Name).Password == oldPassword)
                {
                    _userService.SetPasswordByUserName(CurrentUser.Name, newPassword);
                }
                else
                {
                    throw new Exception("@旧密码输入不正确");
                }

                vmobject.success = true;
                vmobject.msg = "操作成功!";
            }
            catch (Exception ex)
            {
                vmobject.success = false;
                vmobject.msg = ex.Message;
            }

            return Json(vmobject, "text/html");
        }

        public ActionResult ChangeProfile()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ChangeProfile(FormCollection input)
        {
            return View();
        }

        [Authorize]
        public ActionResult Index()
        {
            var model = new ViewModel();
            model.User = new UserViewModel(System.Web.HttpContext.Current.Items[typeof(IUser).FullName] as IUser);

            //add by liubingdi
            ViewBag.JsonData = MvcHtmlString.Create(ListExtensions.ListToJson("menus",
                                                                              KasierMenus.GetAllMenus(
                                                                                  Server.MapPath("~/Configs/XmlMenu.xml"),
                                                                                  "Root")));

            return View(model);
        }

        public ActionResult Login()
        {
            //  CaptchaUtil.Create();
            return View();
        }

        public ActionResult LoginOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login");

        }

        public ActionResult Captcha()
        {
            var image = new CaptchaImage();
            Session[CaptchaUtil.DefaultKey] = image.CaptchaValue;
            var r = new ImageResult(image.CaptchaBitmap);
            return r;
        }

        private User SignIn()
        {
            return null;
        }

        [HttpPost]
        public ActionResult Login(string username, string password, string vaildCode)
        {
            var result = new JsonReturnMessages();
            var errMsg = new List<string>();

            if (!CaptchaUtil.Check(vaildCode))
            {
                result.success = false;
                result.msg = "验证码输入错误。";
            }
            else
            {
                if (_userService.IsExists(username))
                {
                    if (_userService.SignIn(() => _userService.GetNormalUser(username, password)
                                            , (u) => FormsAuthentication.SetAuthCookie(u.Name, true)))
                    {
                        result.success = true;
                    }
                    else
                    {

                        result.success = false;
                        result.msg = "登陆失败，用户名或密码错误。";
                    }
                }
                else
                {
                    errMsg.Add("用户名不存在！");

                    result.success = false;
                    result.msg = string.Join("\r\n", errMsg.ToArray());
                }
            }


            return Json(result);
        }


        #region 用户管理
        public ActionResult UserList()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UserList(UserSearch search, PagingInfo pageinfo)
        {
            var result = this._userService.GetList(search, pageinfo);
            return Content(result.ToJsonString());
        }

        #endregion

        #region 角色管理
        public ActionResult RoleList()
        {
            return View();
        }
        #endregion

        #region 字典管理
        public ActionResult DicList()
        {
            return View();
        }
        #endregion


        public ActionResult AddUser()
        {
            return View("AddUser", new UserBasic());
        }

        [HttpPost]
        public ActionResult AddUser(UserBasic model)
        {
            var vmobject = new JsonReturnMessages();

            try
            {
                model.UserType = 4;
                model.DeptID = "100001";
                model.AccountState = 0;
                model.CreateUserName = CurrentUser.Name;
                model.CreateUserFullName = CurrentUser.DisplayName;
                model.CreateDateTime = DateTime.Now;
                model.LastUpdateTime = DateTime.Now;
                model.LastUpdateUserFullName = CurrentUser.DisplayName;
                model.LastUpdateUserName = CurrentUser.Name;
                _systemManageService.InsertUser(model);

                vmobject.success = true;
                vmobject.msg = "操作成功!";
            }
            catch (Exception ex)
            {
                vmobject.success = false;
                vmobject.msg = ex.Message;
            }

            return Json(vmobject);
        }

        public ActionResult DelUser(string ids)
        {
            var vmobject = new JsonReturnMessages();

            try
            {
                _systemManageService.DeleteUser(ids);

                vmobject.success = true;
                vmobject.msg = "操作成功!";
            }
            catch (Exception ex)
            {
                vmobject.success = false;
                vmobject.msg = ex.Message;
            }

            return Json(vmobject);
        }

        public ActionResult EditUser(string id)
        {
            UserBasic us = (UserBasic)_userService.GetItem(id);
            return View(us);
        }

        public ActionResult Welcome()
        {
            return View();
        }

        [HttpPost]
        public ActionResult EditUser(UserBasic mode)
        {

            var vmobject = new JsonReturnMessages();
            UserBasic us = (UserBasic)_userService.GetItem(mode.UserName);
            UpdateModel(us, Request.Form.AllKeys);
            try
            {
                us.FullName = mode.FullName;
                us.IDCard = mode.IDCard;
                us.Gender = mode.Gender;
                us.Birthday = mode.Birthday;
                us.National = mode.National;
                us.MobilePhone = mode.MobilePhone;
                us.Email = mode.Email;
                us.Sequence = mode.Sequence;
                us.LastUpdateTime = DateTime.Now;
                us.LastUpdateUserFullName = CurrentUser.DisplayName;
                us.LastUpdateUserName = CurrentUser.Name;
                _systemManageService.UpdateUser(us);

                vmobject.success = true;
                vmobject.msg = "操作成功!";
            }
            catch (Exception ex)
            {
                vmobject.success = false;
                vmobject.msg = ex.Message;
            }

            return Json(vmobject);
        }
    }
}
